/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.comleader.operator.core.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.comleader.operator.core.handler.EntityInsertListener;
import com.comleader.operator.core.handler.EntityUpdateListener;
import com.comleader.operator.pojo.entity.BaseEntity;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.audit.MessageCollector;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class MybatisFlexConfig implements MyBatisFlexCustomizer {

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        flexGlobalConfig.registerInsertListener(new EntityInsertListener(), BaseEntity.class);
        flexGlobalConfig.registerUpdateListener(new EntityUpdateListener(), BaseEntity.class);
    }

    @ConditionalOnProperty(name = "mybatis-flex.global-config.sql", havingValue = "true")
    @Bean
    public void sqlLogEnable() {
        AuditManager.setAuditEnable(true);
        MessageCollector collector = new ConsoleMessageCollector();
        AuditManager.setMessageCollector(collector);
        AuditManager.setMessageCollector(auditMessage -> log.info("{},{}ms", auditMessage.getFullSql(), auditMessage.getElapsedTime()));
    }
}